/**
 * @type protype
 */
export default class c_Array<T> {
    /**
     * 移除数组中的指定内容，用于不是对象素组
     * @param str 删除内容
     * @example
     * let arr = new Array<string>()
     * arr.push("1")
     * arr.push("2")
     * arr.remove("1")
     */
    remove(item: (val: T) => any) {
        //@ts-ignore
        const _this: Array<any> = this
        for (let i = _this.length - 1; i >= 0; i--) {
            if (typeof item === 'function') {
                if (item(_this[i])) _this.splice(i, 1)
            } else {
                if (_this[i] === item) _this.splice(i, 1)
            }
        }
    }

    /**
     * 去重
     * @param predicate 比较说明
     * @returns
     * @example
     * const arr1 = arr.toSet()
     * const arr2 = arr.toSet((next,pre)=>next.id===pre.id)
     */
    toSet(predicate?: (next: T, pre: T) => any) {
        const _this: Array<any> = this as any
        if (predicate === undefined)
            predicate = (next: any, pre: any) => {
                return next === pre
            }
        return _this.filter((next, index, arrTemp) => {
            return (
                arrTemp.findIndex((pre) => {
                    return predicate(next, pre)
                }) === index
            )
        })
    }

    /**
     * 随机排序
     */
    randSort() {
        const _this: Array<any> = this as any
        for (var i = 0, len = _this.length; i < len; i++) {
            var rand = parseInt(Math.random() * len + '')
            var temp = _this[rand]
            _this[rand] = _this[i]
            _this[i] = temp
        }
    }

    /**
     * 累加
     * @param field -对象字段名称
     * @example
     * const num = arr.sum()
     * const num = arr.sum('num')
     */
    sum(field?: string) {
        const _this: Array<any> = this as any
        if (_this.length > 0) {
            let num = _this[0]
            for (var i = 1, len = _this.length; i < len; i++) {
                num += field ? _this[i][field] : _this[i]
            }
            return num
        }
        return 0
    }
}
